package com.hcc.plugindust.data.datastore


import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.yc.jetpacklib.data.datastore.YcDataStore
import com.yc.jetpacklib.extension.ycIsEmpty
import com.yc.jetpacklib.extension.ycToNoEmpty

/**
 *  用户信息 dataStore用的key
 */
object UserInfoDataStoreKey {
    var KEY_USER_NAME = stringPreferencesKey("plugin_labour_key_user_name")
    val KEY_USER_ACCOUNT = stringPreferencesKey("plugin_labour_key_user_account")
    val KEY_USER_PASSWORD = stringPreferencesKey("plugin_labour_key_user_password")
    val KEY_USER_ID = stringPreferencesKey("plugin_labour_key_user_id")
    val KEY_USER_TOKEN = stringPreferencesKey("plugin_labour_key_user_token")


    /**
     * 用户是否已登录
     */
    val KEY_USER_IS_LOGGED_IN = booleanPreferencesKey("plugin_labour_key_user_is_logged_in")

    /**
     * 用户在首页选中的项目ID
     */
    val KEY_TEMP_SELECTED_PRO_ID = stringPreferencesKey("plugin_labour_key_temp_selected_pro_id")

    /**
     * 保存登录状态
     * @param account String?   账号 空则不变，用于自动登录
     * @param password String?  密码  同上
     * @param token String      hcc账号token
     */
    suspend fun saveLoginState(account: String? = null, password: String? = null) {
        YcDataStore.save(KEY_USER_IS_LOGGED_IN, true)
        account?.let {
            YcDataStore.save(KEY_USER_ACCOUNT, account)
        }
        password?.let {
            YcDataStore.save(KEY_USER_PASSWORD, password)
        }
    }


    /**
     * 保存登录状态
     * @param account String?   账号 空则不变，用于自动登录
     * @param password String?  密码  同上
     * @param token String      hcc账号token
     */
    suspend fun getPwd(): String {
        var pwd = ""
        YcDataStore.get(KEY_USER_PASSWORD) {
            if (!it.ycIsEmpty())
                pwd = it!!
        }
        return pwd
    }

    /**
     * 保存首页选中的项目ID
     * @param proId String?   项目ID

     */
    suspend fun saveTempSelectedProId(proId: String?) {
        YcDataStore.save(KEY_TEMP_SELECTED_PRO_ID, proId.ycToNoEmpty())
    }

    /**
     * 清除登录状态
     */
    suspend fun clearLoginState() {
        YcDataStore.save(KEY_USER_IS_LOGGED_IN, false)
        YcDataStore.save(KEY_TEMP_SELECTED_PRO_ID, "")
        YcDataStore.save(KEY_USER_PASSWORD, "")
    }

    /**
     * 退出登录
     */
    suspend fun logOut() {
        YcDataStore.save(KEY_USER_IS_LOGGED_IN, false)
        YcDataStore.save(KEY_USER_PASSWORD, "")
    }
}